package com.auok;

import Util.WebUtil;
import com.auok.Command.SendToUserCommand;
import com.auok.Entity.UserSession;
import com.auok.Request.PushMessageRequest;
import com.auok.Response.ApiResult;
import com.auok.Response.PushMessageResponse;
import io.vertx.reactivex.ext.sql.SQLClient;
import io.vertx.reactivex.ext.web.MIMEHeader;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import io.vertx.reactivex.ext.web.handler.BodyHandler;

public class MessageController {
    private SQLClient sqlClient;

    public MessageController(SQLClient sqlClient) {
        this.sqlClient = sqlClient;
    }

    void Register(Router router) {
        router.route().handler(BodyHandler.create());
        router.post("/api/server/pushmessage").handler(this::handlePushMessage);
    }

    private void handlePushMessage(RoutingContext rc) {

        PushMessageRequest request = WebUtil.getJsonBodyToModel(rc, PushMessageRequest.class);

        UserSession toUserSession = ShareData.userSessions.get(request.toUserId);

        //仅发送在线消息，但是用户不在线
        if (toUserSession == null && request.onlyOnline) {
            WebUtil.responseJsonByModel(rc, new ApiResult(false,
                    "用户不在线",
                    new PushMessageResponse(false, false)));
            return;
        }

        SendToUserCommand command = new SendToUserCommand(request.toUserId
                , request.content);

        var msg = command.Exec(request.toUserId);

        msg.Save(sqlClient);

        boolean userOnline = toUserSession != null && toUserSession.getWebSocket() != null;
        String message = "消息送达";

        if (!userOnline) {
            message = "用户离线，消息已保存";
        }

        WebUtil.responseJsonByModel(rc, new ApiResult(
                        true
                        , message,
                        new PushMessageResponse(userOnline, msg.isReceived())
                )
        );
    }
}
